package com.way.demo.filter;

import cn.hutool.core.io.IoUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author itw_xiawx
 * @since 2019/08/30
 */
 public  class ReaderReuseHttpServletRequestWrapper2 extends HttpServletRequestWrapper {

        private final byte[] requestParam;

        public ReaderReuseHttpServletRequestWrapper2(HttpServletRequest request)
                throws IOException {
            super(request);
            requestParam= IoUtil.read(request.getReader()).getBytes(Charset.forName("UTF-8"));
            // body = IOUtils.toString(request.getReader()).getBytes(Charset.forName("UTF-8"));
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(getInputStream()));
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream bais = new ByteArrayInputStream(requestParam);
            return new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {

                }

                @Override
                public int read() throws IOException {
                    return bais.read();
                }
            };
        }
}
